var permisson = require('../../utils/permisson.js');
var lockHelper = require('../../utils/yx2-lock/lockHelper')
const bluetoothManager = require("../../utils/bluetooth.wechart").bluetoothManager;
var { PluginManager } = require("../../utils/BLELock.js");
const blePermissionName = 'scope.bluetooth'; // 蓝牙对应的权限名称
const blePermissionZhName = '蓝牙'; // 蓝牙权限对应的中文名称
let that, tagName = 'index'
var bleManager, pluginManager
// 引入插件
// v1.14.0及以前版本
// const Plugin = requirePlugin("myPlugin");
// v1.15.0及以上版本
const createPlugin = requirePlugin("myPlugin");
const Plugin = createPlugin()
var initKeyGroupId = 903
// 定义数据
// var config = {
//   keyGroupId: 903,  // 由业务服务器返回
//   lockMac: "806fb05189e0",  // 通过API: getBroadcastData 获得
//   aesKey: "cj8CO8PWkBdS6EcG", // 通过API: addBluetoothDevice 获得
//   authCode: "59d13a2d", // 通过API: addBluetoothDevice 获得
// };
var socketToken = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJwaG9uZVwiOlwiMTM5MDAwMDAwMDBcIixcImlmQWRtaW5cIjoxLFwidXNlclR5cGVcIjoxLFwiYXV0aFFPcGVuSWRcIjpcIk1pMHhOamsyT0RRek1ETTJOVEU1Smprd09EZ3dOelF3TnprNE1UazFOekV5TUE9PVwifSIsImlzcyI6IkF1dGhRIiwiZXhwIjoxNzA3MzcxNDc4LCJpYXQiOjE3MDM3NzE0NzgsImp0aSI6IjgyOTQ5NjgyNTQ0In0.M9l21b0tzXdyw4ZsF-sXOPKsEnLyVDOIAUUO-063X3I'
var socketTask
var cReconnectCount = 0
var MaxReconnectCount = 3
var heartBeatInterval
Page({
  /**
   * 页面的初始数据
   */
  data: {
    h5url: "http://122.234.51.39:10001/mobile2/packages/loginPack/center/index"
  },
  onLoad: function() {
    that = this
    console.log('index', 'onLoad')
    permisson.permission_request(blePermissionName, blePermissionZhName, result => {
      that.data.hasBlePermission = result
      console.log(tagName, '蓝牙权限请求' + result ? '成功' : '失败')
      
    });
    that.connectSocket()
  },
  doCommonTask: function(tag, promiseAction) {
    console.log(tagName, tag)
    promiseAction()
    .then(res => {
      var cacheRes = {
        "type": responseData.modal,
        "form": 'mp',
        "modal": responseData.modal,
        "params": res
      }
      var response = {
        "type": responseData.modal,
        "responseData": JSON.stringify(cacheRes)
      }
      console.log(tagName, tag + '回复', response)
      return socketTask.send({"data": JSON.stringify(response)})
    }).then(res => {
      console.log(tagName, tag + '回复成功', res)
    }).catch(err => {
      console.log(tagName, tag + '扫码回复失败', err)
    })
  },
  connectSocket: function() {
    clearInterval(heartBeatInterval)
    socketTask = wx.connectSocket({
      url: 'ws://122.234.51.39:10001/api/yx2-websocket/server',
      protocols: [socketToken],
      success: (res) => {
        console.log(tagName, 'connect success', res)
      },  
      fail: (err) => {
        console.log(tagName, 'connect fail', err)
      }
    })
    socketTask.onOpen(res => {
      console.log(tagName, 'onOpen', res, 'socketTask', socketTask)
      heartBeatInterval = setInterval(() => {
        var heartBeatData = {
          "type": 0,
          "form":"mp",
          "modal":"HeartBeat",
          "params":{
          
          }}
        console.log(tagName, 'send hearbeat', heartBeatData)
        socketTask.send({
          data: JSON.stringify(heartBeatData)
        }).then(res => {
          console.log(tagName, 'send heartbeat success', res)
        }).catch(err => {
          console.log(tagName, 'send heartbeat err', err)
          console.log(tagName, 'send heartbeat err', 'cReconnectCount:' + cReconnectCount, 'MaxReconnectCount:' + MaxReconnectCount)
          if (cReconnectCount > MaxReconnectCount) {
            console.log(tagName, 'send heartbeat,onError,已尝试最大重连次数')
            return
          }
          that.onnectSocket()
          cReconnectCount ++
        })
      }, 5000);
    })
    socketTask.onMessage(res => {
      //data: "{"type":1000,"responseData":"{\"type\":1000,\"form\":\"h5\",\"modal\":\"scan\",\"params\":{\"a\":1,\"b\":2,\"c\":3}}"}"
      console.log(tagName, 'onMessage', res)
      var data = JSON.parse(res.data)
      console.log(tagName, 'onMessage,parsedata', data)
      var responseData = JSON.parse(data.responseData)
      var params = responseData.params
      if (responseData.form == 'h5') {
        if (responseData.modal == 'common_scan') {
          that.doCommonTask('打开扫码', () => { return wx.scanCode()})
        } else if (responseData.modal == 'common_requestPayment') {
          /* //params对象示例
          {
            timeStamp: '',
            nonceStr: '',
            package: '',
            signType: '',
            paySign: '',
          } */
          that.doCommonTask('调用通用支付', () => {
            return wx.requestPayment(params)
          })
        } else if (responseData.modal = 'blePlugin_addLock') {
          that.doCommonTask('添加锁', () => {
            return new Promise(resolve => {
              that.initBlePlugin(() => {
                resolve()
              }, initKeyGroupId)
            }).then(res => {
              return that.plugin.addBluetoothDevice()
            }).then(res => {
              return that.plugin.validateLockInitialInfo({
                isSuccess: true
              })
            })
          })
        } else if (responseData.modal = 'blePlugin_initBlePlugin') {
          /* //params对象示例
          {
            keyGroupId: '',
            authCode: '',
            aesKey: '',
            lockMac: ''
          } */
          that.doCommonTask('初始化蓝牙插件', () => {
            return new Promise(resolve => {
              that.initBlePlugin(res=> {
                console.log(tagName, 'initBlePluginClick', 'ok')
                resolve(res)
              }, params.keyGroupId, params.authCode, params.aesKey, params.lockMac)
            })
          })
        } else if (responseData.modal = 'blePlugin_openLock') {
          that.doCommonTask('开锁', () => {
            return that.plugin.openLock()
          })
        } else if (responseData.modal = 'blePlugin_getBroadcastData') {
          that.doCommonTask('获取广播数据', () => {
            return that.plugin.getBroadcastData()
          })
        } else if (responseData.modal = 'blePlugin_addBluetoothDevice') {
          that.doCommonTask('添加蓝牙设备', () => {
            return that.plugin.addBluetoothDevice()
          })
        } else if (responseData.modal = 'blePlugin_validateLockInitialInfo') {
          /* //params对象示例
          {
            isSuccess: true
          } */
          that.doCommonTask('校验门锁初始信息', () => {
            return that.plugin.validateLockInitialInfo({
              isSuccess: true
            })
          })
        } else if (responseData.modal = 'blePlugin_synchronizeLockSystemTime') {
          that.doCommonTask('同步门锁系统时间', () => {
            return that.plugin.synchronizeLockSystemTime()
          })
        } else if (responseData.modal = 'blePlugin_readDNAInfo') {
          that.doCommonTask('读取DNA信息', () => {
            return that.plugin.readDNAInfo()
          })
        } else if (responseData.modal = 'blePlugin_readSystemInfo') {
          that.doCommonTask('读取系统参数', () => {
            return that.plugin.readSystemInfo()
          })
        } else if (responseData.modal = 'blePlugin_setSystemInfo') {
          /* //params对象示例
          {
            openMode: 1,
            normallyOpenMode: 1,
            volumeEnable: 1,
            systemVolume: 1,
            shackleAlarmEnable: 1,
            lockCylinderAlarmEnable: 1,
            antiLockEnable: 1,
            lockCoverAlarmEnable: 1,
            systemLanguage: 1
          } */
          that.doCommonTask('设置系统参数', () => {
            return that.plugin.setSystemInfo(params)
          })
        } else if (responseData.modal = 'blePlugin_enableKey') {
          /* //params对象示例
          {
            mode: 1,
            lockKeyId: 11,
            value: true
            // mode: 2,
            // value: {
            //   password: true,
            // }
            // mode: 3,
            // keyGroupId: config.keyGroupId,
            // value: true
          } */
          that.doCommonTask('钥匙的使能与禁止', () => {
            return that.plugin.enableKey(params)
          })
        } else if (responseData.modal = 'blePlugin_addKey') {
          /* params为options1或options2对象
          // 有效日期
          var validStartTime = new Date("2018-12-24");
          validStartTime.setHours(9, 12, 23);
          validStartTime = Math.floor(validStartTime.getTime() / 1000);
          // 结束日期
          var validEndTime = new Date("2019-12-25");
          validEndTime.setHours(9, 12, 23);
          validEndTime = Math.floor(validEndTime.getTime() / 1000);
          var lockKeyId = 888; // 钥匙ID由设备分配
          var keyGroupId = config.keyGroupId; // 用户组ID
          var usageCount = 30; // 使用次数
          var options1 = {
            lockKeyId,
            keyGroupId,
            validStartTime,
            validEndTime,
            usageCount,
            type: 0, // 按指定的钥匙类型添加
            keyType: 2, // 卡片类型
            validTimeMode: 0 // 时间模式为有效期类型
          };
          // this.plugin
          //   .addKey(options1)
          //   .then(function(res) {
          //     console.log("addKey1 res -->", res);
          //   })
          //   .catch(function(err) {
          //     console.log("addKey1 err -->", err);
          //   });
          var options2 = {
            lockKeyId,
            keyGroupId,
            validStartTime,
            validEndTime,
            usageCount,
            type: 1, // 按内容添加
            keyType: 1, // 密码类型
            validTimeMode: 0, // 时间模式为有效期类型
            key: "123123" // 内容值
            // validTimeMode: 1, // 时间模式为重复周期类型
            // dayStartTime: 10 * 60, // 起始分钟数
            // dayEndTime: 22 * 60, // 结束分钟数
            // weeks: [1, 2, 3, 4] // 每周的周二、周四、周五
          }; */
          that.doCommonTask('添加钥匙', () => {
            return that.plugin.addKey(params)
          })
        } else if (responseData.modal = 'blePlugin_removeKey') {
          /* //params对象示例
          {
            mode: 0,
            lockKeyId: 11,
            keyType: [1]
            // mode: 1,
            // keyType: [1, 2]
            // mode: 2,
            // keyType: [1],
            // key: '123123',
            // mode: 3,
            // keyGroupId: config.keyGroupId
          } */
          that.doCommonTask('删除钥匙', () => {
            return that.plugin.removeKey(params)
          })
        } else if (responseData.modal = 'blePlugin_updatePassword') {
          /* //params对象示例
          {
            newPassword: "222223",f
            lockKeyId: 11
          } */
          that.doCommonTask('修改密码', () => {
            return that.plugin.updatePassword(params)
          })
        } else if (responseData.modal = 'blePlugin_releaseAlarm') {
          /* //params对象示例
          {
            releaseAlarmType: 255
          } */
          that.doCommonTask('解除报警', () => {
            return that.plugin.releaseAlarm(params)
          })
        } else if (responseData.modal = 'blePlugin_synchronizeKeyList') {
          that.doCommonTask('同步钥匙列表', () => {
            return that.plugin.synchronizeKeyList()
          })
        } else if (responseData.modal = 'blePlugin_removeBluetoothDevice') {
          that.doCommonTask('删除蓝牙设备', () => {
            return that.plugin.removeBluetoothDevice()
          })
        } else if (responseData.modal = 'blePlugin_synchronizeLockRecord') {
          that.doCommonTask('同步门锁记录', () => {
            return that.plugin.synchronizeLockRecord()
          })
        } else if (responseData.modal = 'blePlugin_addRemoteControl') {
          /* //params对象示例
          {
            type: "NB",
            tokenId: config.loginToken
          } */
          that.doCommonTask('添加远程控制', () => {
            return that.plugin.addRemoteControl(params)
          })
        } else if (responseData.modal = 'lockHelper_queryLockInfo') {
          that.doCommonTask('查询锁信息', () => {
            /* //params对象示例
            {
              houseId: "",
              isGuestRoom: false
            } */
            return lockHelper.queryLockInfo(params.houseId, params.isGuestRoom)
          })
        } else if (responseData.modal = 'lockHelper_doOperate') {
          /* //params对象示例
            {
              operateKey: '',
              houseId: '',
              isGuestRoom: false,
              otherParams: null,
              hideLoading: true
            } 
            // 开锁
            if (operateKey === "openLock") {
              return openLock(houseId, isGuestRoom)
            } else if (operateKey === "openLockByRemote") {
              // 远程开门
              return openLockByRemote(houseId, isGuestRoom, otherParams, hideLoading)
            } else if (operateKey === "readDNAInfo") {
              return readDNAInfo(houseId, isGuestRoom)
            }
            // 同步系统时间
            else if (operateKey === "synchronizeLockSystemTime") {
              return synchronizeLockSystemTime(houseId, isGuestRoom, hideLoading)
            }
            // 添加门卡
            else if (operateKey === "addKey") {
              return addKey(houseId, isGuestRoom, otherParams)
            }
            // 添加门卡准备
            else if (operateKey === "addKeyPre") {
              return addKeyPre(houseId, isGuestRoom, otherParams)
            }
            // 删除门卡准备
            else if (operateKey === "removeKeyPre") {
              return removeKeyPre(houseId, isGuestRoom, otherParams)
            } else if (operateKey === "removeUserPre") {
              return removeUserPre(houseId, isGuestRoom, otherParams)
            }
            // 启用钥匙
            // otherParams中要传id
            else if (operateKey === "enableKey") {
              return enableKey(houseId, isGuestRoom, otherParams)
            }
            // 远程激活钥匙
            else if (operateKey === "activeKey") {
              return activeKey()
            }
            // 禁用钥匙
            // otherParams中要传id
            else if (operateKey === "disableKey") {
              return disableKey(houseId, isGuestRoom, otherParams)
            }
            // 删除门卡
            else if (operateKey === "removeKey") {
              return removeKey(houseId, isGuestRoom, otherParams)
            }
            // 删除设备
            else if (operateKey === "removeBluetoothDevice") {
              // 蓝牙删除钥匙
              return removeBluetoothDevice(houseId, isGuestRoom)
            } // 同步钥匙列表信息
            else if (operateKey === "synchronizeKeyList") {
              // 蓝牙删除钥匙
              return synchronizeKeyList(houseId, isGuestRoom)
            } // 激活钥匙
            else if (operateKey === "upgradeFirmware") {
              // lockConsole.log(`=========>开始执行升级操作【${moment().format("yyyy-MM-DD HH:mm:ss")}】`)
              // return upgradeFirmwareOTA(houseId, isGuestRoom, otherParams)

              if (otherParams && otherParams.chipType.toString() === "3") {
                return upgradeFirmwareDFU(houseId, isGuestRoom, otherParams)
              } else {
                return upgradeFirmwareOTA(houseId, isGuestRoom, otherParams)
              }
            } else if (operateKey === "cancelUpgradeFirmware") {
              // 升级固件版本
              return cancelUpgradeFirmware()
            }
            */
          that.doCommonTask('操作集合', () => {
            return lockHelper.doOperate(params.operateKey, params.houseId, params.isGuestRoom, params.otherParams, params.hideLoading)
          })
        } else if (responseData.modal = 'lockHelper_disconnect') {
          that.doCommonTask('断开连接', () => {
            return lockHelper.disconnect()
          })
        } else if (responseData.modal = 'bluetoothWechat_init') {
          /* //params对象示例
            {
              lockCode: '',
              lockId: '',
            } */
          that.doCommonTask('微信蓝牙初始化', () => {
            return new Promise(resolve => {
              that.bleManager = new bluetoothManager({
                lockCode: params.lockCode,
                lockId: params.lockId,
                onSuccess: (lockManager) => {
                  console.log('----------微信蓝牙初始化成功回调----------', 'lockManager', lockManager)
                  resolve()
                }
              })
            })
          })
        } else if (responseData.modal = 'bluetoothWechat_doOpen') {
          that.doCommonTask('微信蓝牙开锁', () => {
            return new Promise((resolve, reject) => {
              if (!that.bleManager) {
                reject({
                  code: -1,
                  errMsg: 'bleManager没有初始化'
                })
                return
              }
              that.bleManager.doOpen(() => {
                resolve()
              })
            })
          })
        } else if (responseData.modal = 'BleLock_init') {
          /* //params对象示例
            {
              authCode: '',
              aesKey: '',
              lockMac: '',
              keyGroupId: ''
            } */
          that.doCommonTask('BleLock初始化', () => {
            return new Promise(resolve => {
              that.pluginManager = new PluginManager({			
                authCode: params.authCode,
                aesKey: params.aesKey,
                lockMac: params.lockMac,
                keyGroupId: params.keyGroupId,
                ready: data => {
                  console.log('----------BleLock初始化成功回调----------', 'data', data)
                  resolve()
                },
              });
            })
          })
        } else if (responseData.modal = 'BleLock_addKey') {
          /* //params对象示例
            {
              keyGroupId: this.config.keyUserId,
              usageCount: 255,
              type: 0,
              // 按内容添加
              keyType: 0,
              // 密码类型  指纹	0   密码	1  卡片	2
              validTimeMode: 0,
              // 时间模式为有效期类型
              validStartTime,
              validEndTime
            } */
          that.doCommonTask('BleLock添加钥匙', () => {
            return new Promise((resolve, reject) => {
              if (!that.pluginManager) {
                reject({
                  code: -2,
                  errMsg: 'pluginManager没有初始化'
                })
                return
              }
              that.pluginManager.addKey(() => {
                resolve()
              })
            })
          })
        }
      } 
    })
    socketTask.onError(res => {
      console.log(tagName, 'onError', res)
      console.log(tagName, 'onError', 'cReconnectCount:' + cReconnectCount, 'MaxReconnectCount:' + MaxReconnectCount)
      if (cReconnectCount >= MaxReconnectCount) {
        console.log(tagName, 'onError,已尝试最大重连次数')
        return
      }
      that.connectSocket()
      cReconnectCount ++
    })
    socketTask.onClose(res => {
      console.log(tagName, 'onClose', res)
      console.log(tagName, 'onClose', 'cReconnectCount:' + cReconnectCount, 'MaxReconnectCount:' + MaxReconnectCount)
      if (cReconnectCount > MaxReconnectCount) {
        console.log(tagName, 'onClose,已尝试最大重连次数')
        return
      }
      connectSocket()
      cReconnectCount ++
    })
  },
  initBlePlugin: function(onReadyAction, keyGroupId, authCode, aesKey, lockMac) {
    var tag = 'initBlePlugin'
    if (!keyGroupId) {
      console.log(tagName, tag, 'err,keyGroupId is null')
      return
    }
    console.log(tagName, tag, 'authCode:' + authCode, 'aesKey:' + aesKey, 'lockMac:' + lockMac, 'keyGroupId:' + keyGroupId)
    if (authCode && aesKey && lockMac) {
      that.plugin = new Plugin({
        authCode: authCode,
        aesKey: aesKey,
        lockMac: lockMac,
        keyGroupId: keyGroupId
      });
    } else {
      that.plugin = new Plugin({
        keyGroupId: initKeyGroupId
      });
    }
    that.plugin.on("ready", function(plugin) {
      console.info("plugin is on ready", plugin);
      onReadyAction(plugin.config)
    });
    // 监听“断开连接”事件
    that.plugin.on("close", function(state) {
      console.info(tag, "plugin is on close, state -->", state);
    });
    // 监听“运行错误”事件
    that.plugin.on("error", function(err) {
      console.info(tag, "plugin is on error -->", err);
    });
    // 监听“开锁”事件上报
    that.plugin.on("report:openLock", function(data) {
      console.info(tag, "plugin is on opened lock, data is ", data);
    });
    // 监听“钥匙的使能与禁止”事件上报
    that.plugin.on("report:enableKey", function(data) {
      console.info(tag, "plugin is on enabled key, data is ", data);
    });
    // 监听“添加钥匙”事件
    that.plugin.on("addKey", function(data){
      console.log(tag, 'plugin is on addKey, data is ', data)
    })
    // 监听“删除钥匙”事件上报
    that.plugin.on("report:removeKey", function(data) {
      console.info(tag, "plugin is on remove key, data is ", data);
    });
    // 监听“添加钥匙”事件上报
    that.plugin.on("report:addKey", function(data) {
      console.info(tag, "plugin is on add key, data is ", data);
    });
    // 监听“设置系统参数”事件上报
    that.plugin.on("report:setSystemInfo", function(data) {
      console.info(tag, "plugin is on set system info, data is ", data);
    });
    // 监听“修改密码”事件上报
    that.plugin.on("report:updatePassword", function(data) {
      console.info(tag, "plugin is on updating password, data is ", data);
    });
  },
  onH5MsgReceived: function(e) {
    console.log(tagName, 'onH5MsgReceived', e)
    socketToken = e.detail.data.token
    that.connectSocket()
  },
  //添加锁并校验信息
  addLock: function() {
    var tag = 'addLock'
    console.log(tagName, tag)
    that.initBlePlugin(() => {
      that.plugin.addBluetoothDevice()
      .then(res => {
        console.log('addBluetoothDevice success', res)
        return that.plugin.validateLockInitialInfo({
          isSuccess: true
        })
      }).then(res => {
        console.log('validateLockInitialInfo success', res)
      }).catch(err => {
        console.log('addBluetoothDevice or validateLockInitialInfo err,', err)
      })
    }, initKeyGroupId)
  },
  initBlePluginClick: function() {
    that.initBlePlugin(res => {
      console.log(tagName, 'initBlePluginClick', 'ok', res)
    }, '0387', '6a698977', 'VKbsmSPJSxvTeAPw', '685d5f11a62f')
  },
  openLock: function() {
    that.plugin.openLock()
  }
 });